package com.hula.onion.book.server.spider.platforms.renzhongjinfu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by work on 2018/3/19.
 */
@Component("renZhongJFSpider")
public class RenZhongJFSpider extends SpiderCommon {

    @Autowired
    private RenZhongJFSpiderHelper spiderHelper;

    private static final String LOGIN_URL = "https://www.51rz.com/apiPc/user/login.html";

    private static final String ACCOUNT_INFO_URL = "https://www.51rz.com/apiPc/accountPage/accountIndex.html";

    @Override
    public CommonResponse execute() {
        String loginStr = HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if (StringUtils.isEmpty(loginStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        JSONObject loginJson = JSON.parseObject(loginStr);
        if ("000000".equals(loginJson.getString("responseCode"))) {
            JSONObject jsonObject = loginJson.getJSONObject("obj");
            String token = jsonObject.getString("token");
            String accountJson = HttpUtils.post(ACCOUNT_INFO_URL,
                    spiderHelper.installAccountRequestParams(token),
                    getHttpContext());
            return spiderHelper.parseAccountBalance(accountJson);

        } else if ("999999".equals(loginJson.getString("responseCode"))) {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }
}
